<script lang="ts" setup>
import {nextTick, onBeforeUnmount, onMounted} from "vue";
import { ref, defineProps, defineExpose, watch } from 'vue';
import * as echarts from "echarts";
import * as Api from '@/api/class'
interface User {
  date: string
  name: string
  address: string
}
const props = defineProps({
  studentId: {
    type: String,
    required: true
  }
})

const homeworkIds = ref([])
const studentScores = ref([])
const myChart = ref(null)
const isLoading = ref(false)

// 获取作业ID列表
// 获取作业ID列表
// 获取作业ID列表
const fetchHomeworkIds = async () => {
  try {
    console.log('开始获取作业ID列表...')
    const res = await Api.hilist()
    homeworkIds.value = res.data || []
    console.log('获取到的作业ID列表:', homeworkIds.value)
  } catch (error) {
    console.error('获取作业ID失败:', error)
  }
}

// 获取学生成绩
const fetchStudentScores = async () => {
  if (!props.studentId) {
    console.warn('studentId为空，跳过获取成绩')
    return
  }

  if (homeworkIds.value.length === 0) {
    console.warn('作业ID列表为空，请先获取作业ID')
    return
  }

  isLoading.value = true
  studentScores.value = []

  try {
    console.log('开始获取学生成绩，studentId:', props.studentId)
    console.log('使用的作业ID列表:', homeworkIds.value)

    const requests = homeworkIds.value.map(homeworkId => {
      console.log(`请求参数 - stuId:${props.studentId}, homeworkId:${homeworkId.id || homeworkId}`)
      return Api.score({
        stuId: props.studentId,
        homeworkId: homeworkId.id || homeworkId  // 兼容两种数据结构
      })
    })

    const responses = await Promise.all(requests)
    console.log('API响应数据:', responses)

    studentScores.value = responses.map(res => {
      const score = res.data?.score ?? res.data  // 兼容不同响应结构
      console.log('解析出的分数:', score)
      return Number(score) || 0  // 确保转换为数字
    })

    console.log('最终成绩数组:', studentScores.value)
    await nextTick()
    renderChart()
  } catch (error) {
    studentScores.value = homeworkIds.value.map(() => 0)  // 出错时填充0
  } finally {
    isLoading.value = false
  }
}

// 渲染图表（添加了y=425的标记线）
const renderChart = () => {
  if (!myChart.value) {
    const chartDom = document.getElementById('student-score-chart')
    if (chartDom) {
      myChart.value = (myChart.value || echarts.init(chartDom))
    }
  }

  if (myChart.value ) {
    console.log('渲染图表，数据:', studentScores.value)
    const option = {
      tooltip: {
        trigger: 'axis',
        formatter: '{b}<br/>成绩: {c}分'
      },
      toolbox: {
        feature: {
          saveAsImage: {}
        }
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: homeworkIds.value.map((_, index) => `第${index + 1}次模考`),
      },
      yAxis: {
        type: 'value',
        name: '分数',
        min: 0,
        max: Math.max(425, ...studentScores.value) + 50 // 动态调整Y轴最大值
      },
      series: [
        {
          name: '学生成绩',
          type: 'line',
          data: studentScores.value,
          itemStyle: {
            color: '#409EFF'
          },
          lineStyle: {
            width: 3
          },
          symbolSize: 8
        }
      ],
      // 添加标记线
      markLine: {
        silent: false,  // 允许触发事件
        emphasis: {
          lineStyle: {
            width: 3    // 悬停时加粗
          }
        },
        data: [
          // {
          //   name: '425分数线',
          //   yAxis: 425,  // 在y=425处画线
          //   lineStyle: {
          //     color: '#F56C6C',
          //     width: 2,
          //     type: 'dashed' // 虚线
          //   },
          //   label: {
          //     position: 'end',
          //     formatter: '425分',
          //     color: '#F56C6C'
          //   }
          // }
        ]
      },
    }
    myChart.value.setOption(option, { notMerge: true })
    myChart.value.resize()

  }
}

// 增强的watch监听
watch(() => props.studentId, (newVal, oldVal) => {
  console.log(`studentId变化: ${oldVal} => ${newVal}`)
  if (newVal && newVal !== oldVal) {
    fetchStudentScores()
  }
})

// 初始化
onMounted(async () => {
  console.log('组件挂载')
  await fetchHomeworkIds()
  if (props.studentId) {
    await fetchStudentScores()
  }
})

// // 销毁
// onBeforeUnmount(() => {
//   myChart.value?.dispose()
// })

// 暴露方法
defineExpose({
  refresh: () => {
    console.log('手动刷新成绩数据')
    fetchStudentScores()
  },
  getScores: () => studentScores.value
})
</script>

<template>
  <el-scrollbar height="400px">
    <div style="width: 100%;height: 380px;display: flex;flex-direction: column">
      <div class="student-detail-container">
        <div v-if="isLoading" class="loading-tip">
          <el-icon class="is-loading"><Loading /></el-icon>
          正在加载成绩数据...
        </div>

        <div v-else-if="studentScores.length === 0" class="empty-tip">
          暂无成绩数据
        </div>

        <div
            id="student-score-chart"
            style="width: 100%; height: 380px;"
            v-show="studentScores.length > 0"
        ></div>
      </div>
<!--      <div style="height: 400px;width:100%;display: flex;justify-content: space-around">-->
<!--&lt;!&ndash;        <div  style="width:550px;height:300px">&ndash;&gt;-->
<!--&lt;!&ndash;          <el-table&ndash;&gt;-->
<!--&lt;!&ndash;              :data="tableData"&ndash;&gt;-->
<!--&lt;!&ndash;              style="width: 100%"&ndash;&gt;-->
<!--&lt;!&ndash;              height="350"&ndash;&gt;-->
<!--&lt;!&ndash;              :row-class-name="tableRowClassName"&ndash;&gt;-->
<!--&lt;!&ndash;          >&ndash;&gt;-->
<!--&lt;!&ndash;            <el-table-column prop="date" label="模考名称" width="180" />&ndash;&gt;-->
<!--&lt;!&ndash;            <el-table-column prop="name" label="成绩" width="180" />&ndash;&gt;-->
<!--&lt;!&ndash;            <el-table-column prop="address" label="Address" />&ndash;&gt;-->
<!--&lt;!&ndash;          </el-table></div>&ndash;&gt;-->
<!--        <div id="cjzx" style="width:80%;height:300px"> </div>-->
<!--&lt;!&ndash;        <div v-if="studentScores.length === 0" class="loading">&ndash;&gt;-->
<!--&lt;!&ndash;          正在加载成绩数据...&ndash;&gt;-->
<!--&lt;!&ndash;        </div>&ndash;&gt;-->
<!--      </div>-->

    </div>
  </el-scrollbar>


</template>

<style scoped>
.student-detail-container {
  padding: 15px;
}

.loading-tip {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: var(--el-color-info);
}

.empty-tip {
  text-align: center;
  padding: 50px 0;
  color: var(--el-text-color-secondary);
}
</style>